import os
import logging
from dtos.result import Result
from utils.common_util import CommonUtil
from config import UPLOAD_PATH, FILE_TYPE


class UploadUtil(object):

    def __init__(self):
        self.upload_path = UPLOAD_PATH

    def image_upload(self, files, file_key_list, model):
        """
        上传图片接口，该接口仅支持图片文件上传
        :param files:
        :param file_key_list:
        :param model:
        :return:
        """
        if not files:
            return Result.error_result(message="文件不能为空")
        if not model:
            return Result.error_result(message="model不能为空")
        # if int(file_size) > UPLOAD_MATERIAL_IMAGE_SIZE:
        #     return Result.error_result(message="图片过大，请上传不超过%sKB大小的图片" %
        #                                        str(int(UPLOAD_MATERIAL_IMAGE_SIZE // 1024)))
        res = {}
        file_key = file_key_list[0]
        if file_key not in files.keys() or not files[file_key][0]:
            return Result.error_result(message="文件不能为空，请检查图片文件的key是否为%s" % file_key)
        image = files[file_key][0]
        filename, content_type, body = image['filename'], image['content_type'], image['body']
        file_type = filename.split('.')[-1]
        logging.info("上传文件类型：%s" % file_type)
        if file_type not in FILE_TYPE:
            return Result.error_result(message="文件格式不符合要求")
        # allow_format_list = ["text/plain"]
        # if content_type not in allow_format_list:
        #     return Result.error_result(message="文件格式不符合要求")

        year, month, day = CommonUtil.get_current_year_month_day()
        year, month, day = str(year), str(month), str(day)
        uuid = CommonUtil.generate_guid()
        new_filename = "%s.%s" % (uuid, file_type)
        dir_path = CommonUtil.get_path_by_system_version([self.upload_path, model, year, month, day])
        file_path = CommonUtil.get_path_by_system_version([dir_path, new_filename])
        relative_path = CommonUtil.get_path_by_system_version([model, year, month, day, new_filename])
        try:
            if not os.path.exists(dir_path):
                os.makedirs(dir_path)
            with open(file_path, 'wb') as f:
                f.write(body)
            res[file_key] = {
                "file_path": file_path,
                "relative_path": relative_path,
                "file_name": filename
            }
        except Exception as ex:
            message = "上传文件失败，原因：%s" % str(ex)
            logging.info(message)
            return Result.error_result(message=message)
        return Result.success_result(message="文件上传成功", data=res)

    @classmethod
    def remove_file(cls, file_path):
        """
        删除指定文件
        :param file_path:
        :return:
        """
        try:
            os.remove(file_path)
            return Result.success_result()
        except Exception as ex:
            logging.info("删除文件异常，路径：%s，原因：%s" % (str(file_path), str(ex)))
            return Result.error_result(message="删除失败，没有找到该文件")
